#pragma once
#include"protocol.hpp"

/*业务层，可自定义*/
class calculator
{
public:
    calculator(){}
    respond calculate(request &rq)
    {
        respond ret;
        switch(rq.OPER())
        {
            case '+':
                ret.ANS()=rq.X()+rq.Y();
                ret.CODE()=0;
                break;
            case '-':
                ret.ANS()=rq.X()-rq.Y();
                ret.CODE()=0;
                break;
            case '*':
                ret.ANS()=rq.X()*rq.Y();
                ret.CODE()=0;
                break;
            case '/':
                if(rq.Y()==0){
                    ret.CODE()=DIV_ZERO_ERROR;
                    break;
                }
                ret.ANS()=rq.X()/rq.Y();
                ret.CODE()=0;
                break;
            case '%':
                if(rq.Y()==0){
                    ret.CODE()=DIV_ZERO_ERROR;
                    break;
                }
                ret.ANS()=rq.X()%rq.Y();
                ret.CODE()=0;
                break;
            default:
                ret.CODE()=OPER_ERROR;
        }
        return ret;
    }
    ~calculator(){}
};

calculator cal;

bool execute(std::string &inbuffer,std::string& outbuffer){
    std::string buffer;
    if(!decode(inbuffer,&buffer)) return false;//报文不完整，不做处理
    //将请求进行反序列化
    request rst;
    rst.deSerialize(buffer);

    respond resp;

    resp=cal.calculate(rst);

    //将应答进行序列化。并且发送给对端主机
    resp.Serialize(outbuffer);
    encode(outbuffer);
    return true;
}